// 日志处理
const { create } = require('../../service/v1/log')

const { randStr } = require('../../util/random')

//
const SYS_PROJECT_ID = process.env.SYS_PROJECT_ID
// 请求日志
const reqLog = async (ctx, next) => {
  // 1. 记录请求日志
  const headers = ctx.request.headers ? ctx.request.headers : null
  const body = ctx.request.body ? ctx.request.body : null
  const query = ctx.request.query ? ctx.request.query : null
  // 2. 记录请求数据
  const data = {
    headers,
    body,
    query,
    url: ctx.request.url,
    method: ctx.request.method,
    ip: ctx.request.ip,
  }
  const postData = {
    req_id: ctx.request.headers.req_id,
    owner_id: +SYS_PROJECT_ID,
    module: 'reqLog',
    level: 'info',
    body: data,
  }
  await create(ctx, postData)

  await next()
}
// 响应时间
const timeLog = async (ctx, next) => {
  if (!ctx.request.headers.req_id) {
    ctx.request.headers.req_id = `${randStr(16)}${new Date().getTime()}` // 新增
  }
  const start = Date.now()
  await next() // 需要添加 await 否则第二个请求时会报错
  const end = Date.now()
  const time = end - start

  const data = {
    url: ctx.request.url,
    method: ctx.request.method,
    ip: ctx.request.ip,
    duration: time,
    start: start,
    end: end,
  }
  const postData = {
    req_id: ctx.request.headers.req_id,
    module: 'timeLog',
    level: 'info',
    owner_id: +SYS_PROJECT_ID,
    body: data,
  }
  await create(ctx, postData)
}

const errLog = async (ctx, err) => {
  try {
    // 1. 记录请求日志
    const headers = ctx.request.headers ? ctx.request.headers : null
    const body = ctx.request.body ? ctx.request.body : null
    const query = ctx.request.query ? ctx.request.query : null
    // 2. 记录请求数据
    const data = {
      headers,
      body,
      query,
      url: ctx.request.url,
      method: ctx.request.method,
      ip: ctx.request.ip,
      err: err,
    }
    const postData = {
      req_id: ctx.request.headers.req_id,
      owner_id: +SYS_PROJECT_ID,
      module: 'errLog',
      level: 'error',
      body: data,
    }
    await create(ctx, postData)
  } catch (err) {
    console.log(err)
  }
}

module.exports = {
  reqLog,
  errLog,
  timeLog,
}
